package com.example.qxfw.qxybzz.service.Impl;

import cn.hutool.core.io.FileUtil;
import com.example.qxfw.dysjrh.config.DmgisConfig;
import com.example.qxfw.qxybzz.entity.vo.ImageFile;
import com.example.qxfw.qxybzz.entity.vo.ImageUpdateFile;
import com.example.qxfw.qxybzz.service.ImageService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

@Service
@RequiredArgsConstructor
public class ImageServiceImpl implements ImageService {

    @Qualifier("mongoPrimaryTemplate")
    @Autowired
    private MongoTemplate mongoTemplate;

    private final DmgisConfig dmgisConfig;


    /**
     * 保存图片
     *
     * @param data
     * @param name
     */
    @Override
    public void saveImage(MultipartFile data, String name) {

        try {
            ImageFile imageFile = new ImageFile();
            imageFile.setName(name);
            byte[] aByte = getByte(data);
            imageFile.setData(aByte);
            mongoTemplate.insert(imageFile, "image_file");
        } catch (Exception e) {
            throw new RuntimeException("保存图像失败", e);
        }
    }


    //MultipartFile转换为二进制
    public byte[] getByte(MultipartFile multipartFile) throws IOException {
        byte[] bytes = multipartFile.getBytes();
        return bytes;
    }


    /**
     * 根据图片文字生成图片（将文字叠加到图片中）
     *
     * @param text
     * @param imageId
     */
    @Override
    public void getImage(String text, String imageId) {
        // 根据id查询mongodb里的图片
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(imageId));
        ImageFile imageFile = mongoTemplate.findOne(query, ImageFile.class);
        byte[] imageFileData = imageFile.getData();
        try {
            byte[] bytes = overlayTextOnImage(imageFileData, text);
            // 将图片存入mongoDB中
            ImageUpdateFile imageUpdateFile = new ImageUpdateFile();
            imageUpdateFile.setData(bytes);
            mongoTemplate.insert(imageUpdateFile, "image_update_file");


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将文字叠加到图片上并返回字节数组
     *
     * @param imageBytes 图片的字节数组
     * @param text       要叠加的文字
     * @return 新生成的图片字节数组
     */
    public byte[] overlayTextOnImage(byte[] imageBytes, String text) throws IOException {
        try (InputStream inputStream = new ByteArrayInputStream(imageBytes)) {
            BufferedImage originalImage = ImageIO.read(inputStream);

            // Create a graphics context to draw the text
            Graphics2D g2d = originalImage.createGraphics();

            // 设置抗锯齿以提高文本质量
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            // 设置字体和颜色
            Font font = new Font("SansSerif", Font.BOLD, 50);
            g2d.setFont(font);
            g2d.setColor(Color.red); // 设置字体颜色为红色

            // 计算文本的位置（居中）
            FontMetrics metrics = g2d.getFontMetrics();
            int x = 0; // 文本的左边缘对齐图片的左边缘
            int y = originalImage.getHeight() - metrics.getDescent(); // 文本的底部对齐图片的底部边缘

            // 绘制文本
            g2d.drawString(text, x, y);

            // 释放图形上下文资源
            g2d.dispose();

            // 将修改后的图像写入字节数组输出流
            try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                ImageIO.write(originalImage, "png", outputStream);
                return outputStream.toByteArray();
            }
        }
    }

    /**
     * 根据图片id获取图片
     *
     * @param imageId
     */
    @Override
    public String getImageById(String imageId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(imageId));
        ImageUpdateFile imageUpdateFile = mongoTemplate.findOne(query, ImageUpdateFile.class);

        if (imageUpdateFile == null) {
            return null;
        }
        byte[] imageUpdateFileData = imageUpdateFile.getData();
        String imageName = imageUpdateFile.get_id();

        String fileName = dmgisConfig.getTxtFilePath() + imageName + ".png";
        String imagePath = dmgisConfig.getNgfileUrl() + imageName + ".png";
        // 删除文件
        FileUtil.del(fileName);
        //创建文件
        FileUtil.touch(fileName);
        FileUtil.writeBytes(imageUpdateFileData, new File(fileName));
        return imagePath;

    }


    /**
     * 根据图片编码和文字描述生成新的图片，并返回图片的且存到mongo中
     * @param text
     * @param imageId
     * @return
     */
    @Override
    public ResponseEntity<byte[]> getImage2(String text, String imageId) {
        // 根据id查询mongodb里的图片
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(imageId));
        ImageFile imageFile = mongoTemplate.findOne(query, ImageFile.class);
        byte[] imageFileData = imageFile.getData();

        byte[] bytes = null;
        try {
            bytes = overlayTextOnImage(imageFileData, text);
            // 将图片存入mongoDB中
            ImageUpdateFile imageUpdateFile = new ImageUpdateFile();
            imageUpdateFile.setData(bytes);
            mongoTemplate.insert(imageUpdateFile, "image_update_file");
        } catch (IOException e) {
            e.printStackTrace();
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);

        return ResponseEntity.ok()
                .headers(headers)
                .body(bytes);
    }


}
